import Cookies from 'js-cookie'
import config from '@/config'
import wx from 'weixin-js-sdk'
import { Toast } from 'vant'
import { getJavaSdkConfig,
  getPayOptions } from '../api/wx-api'

export const TOKEN_KEY = 'token'
export const WXCONFIG = 'wx-config'

const { cookieExpires } = config

export const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
  if (token === '' || token === undefined) {
    console.log('晴空cookies')
    clearCookies()
  }
}

export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) return token
  else return false
}
export const clearCookies = () => {
  Cookies.remove('juyou.session.id')
}

export const wxConfig = (data) => {
  if (data === '' || data === undefined) {
    const wxConfig = Cookies.get(WXCONFIG)
    if (wxConfig) return JSON.parse(wxConfig)
    else return false
  } else {
    Cookies.set(WXCONFIG, JSON.stringify(data), { expires: cookieExpires || 1 })
  }
}

/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = (route, homeRoute) => {
  console.log(route, homeRoute, '执行函数')
  let homeItem = { ...homeRoute, icon: homeRoute.meta.icon }
  let routeMetched = route.matched
  if (routeMetched.some(item => item.name === homeRoute.name)) return [homeItem]
  let res = routeMetched.filter(item => {
    return item.meta === undefined || !item.meta.hideInBread
  }).map(item => {
    let meta = { ...item.meta }
    if (meta.title && typeof meta.title === 'function') {
      meta.__titleIsFunction__ = true
      meta.title = meta.title(route)
    }
    let obj = {
      icon: (item.meta && item.meta.icon) || '',
      name: item.name,
      meta: meta
    }
    return obj
  })
  res = res.filter(item => {
    return !item.meta.hideInMenu
  })
  return [{ ...homeItem, to: homeRoute.path }, ...res]
}
/**
 * @param {Array} routers 路由列表数组
 * @description 用于找到路由列表中name为home的对象
 */
export const getHomeRoute = (routers, homeName = 'home') => {
  let i = -1
  let len = routers.length
  let homeRoute = {}
  while (++i < len) {
    let item = routers[i]
    if (item.children && item.children.length) {
      let res = getHomeRoute(item.children, homeName)
      if (res.name) return res
    } else {
      if (item.name === homeName) homeRoute = item
    }
  }
  return homeRoute
}

export const showTitle = (item, vm) => {
  let { title } = item.meta
  if (!title) return
  title = (item.meta && item.meta.title) || item.name
  return title
}

export const phpMenusfilter = (data) => {
  return data
}
export const javaMenusfilter = (data) => {
  return data
}
export const wxCallBack = (fun, debug) => {
  let resultData = wxConfig('')
  if (debug !== true) {
    debug = false
  }
  const url = window.location.href
  const resultUrl = url.substr(0, url.indexOf('#') - 1)
  const g = false
  if (resultData !== false && resultUrl === resultData.url && g) {
    wxJsConfig(resultData, fun, debug)
  } else {
    getJavaSdkConfig().then(ret => {
      let resultData = ret.data.data
      resultData.url = resultUrl
      wxConfig(resultData)
      wxJsConfig(resultData, fun, debug)
    })
  }
}
export const wxJsConfig = (resultData, fun, debug) => {
  const jsApiList = ['showMenuItems', 'addCard', 'hideAllNonBaseMenuItem', 'getLocalImgData', 'downloadImage', 'chooseWXPay', 'chooseImage', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'uploadImage', 'previewImage', 'getLocation', 'openLocation', 'hideMenuItems', 'scanQRCode', 'editAddress', 'startRecord', 'stopRecord', 'uploadVoice', 'updateAppMessageShareData', 'updateTimelineShareData']
  wx.config({
    debug: debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: resultData.appId, // 必填，公众号的唯一标识
    timestamp: resultData.timestamp, // 必填，生成签名的时间戳
    nonceStr: resultData.nonceStr, // 必填，生成签名的随机串
    signature: resultData.signature, // 必填，签名，见附录1
    jsApiList: jsApiList
  })
  wx.ready(fun)
}

export const commonShare = (options) => {
  share({
    title: '沈阳市民卡',
    desc: '专项补贴、专享福利、专属保障',
    link: config.baseUrl + '/#/common-share',
    imgurl: 'https://skv4.oss-cn-hangzhou.aliyuncs.com/cityCard/project/city-card-share.png'
  })
}

export const share = (options) => {
  wxCallBack(function () {
    wx.updateAppMessageShareData({
      title: options.title, // 分享标题
      desc: options.desc, // 分享描述
      link: options.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: options.imgurl, // 分享图标
      success: function () {
        if (typeof options.success === 'function') {
          options.success()
        }
      }
    })
    wx.updateTimelineShareData({
      title: options.title, // 分享标题
      link: options.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: options.imgurl, // 分享图标
      success: function () {
        if (typeof options.success === 'function') {
          options.success()
        }
      }
    })
  })
}

export const getLocation = (fun) => {
  wxCallBack(function () {
    wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        fun(res)
      }
    })
  })
}

export const openAddress = (fun) => {
  wxCallBack(function () {
    wx.openAddress({
      success: function (res) {
        fun(res)
      }
    })
  })
}
export const openLocation = (options) => {
  wxCallBack(function () {
    wx.openLocation({
      latitude: options.latitude, // 纬度，浮点数，范围为90 ~ -90
      longitude: options.longitude, // 经度，浮点数，范围为180 ~ -180。
      name: options.name, // 位置名
      address: options.address, // 地址详情说明
      scale: 20, // 地图缩放级别,整形值,范围从1~28。默认为最大
      infoUrl: options.url // 在查看位置界面底部显示的超链接,可点击跳转
    })
  })
}

export const wxPay = (order, fun) => {
  getPayOptions(order).then(ret => {
    let data = ret.data
    if (data.status === 1) {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', data.result,
        function (res) {
          if (res.err_msg === 'get_brand_wcpay_request:ok') { // 成功回调函数
            return fun(res, 'success')
          } else {
            var resData = res
            // 设置专用属性
            resData['hderrorcode'] = '-1'
            if (typeof (opt.error) === 'function') {
              return fun(resData, 'error')
            }
            if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              Toast.fail('支付取消')
              if (typeof (opt.cancel) === 'function') {
                return fun(resData, cancel)
              }
            } else {
              Toast.fail('支付失败' + res.err_msg)
            }
            return resData
          }
        }
      )
    } else if (data.status === 1201) {
      let self_url = window.location.href.replace(/#/g, '$')
      location.href = config.baseUrl + '/Api/Api/payJmAuth/cid/' + config.company_code + '?rurl=' + self_url
    } else {
      Toast.fail(data.msg)
    }
  })
}

export const wxPayNew = (val, fun) => {
  let data = {
    appId: val.appId,
    nonceStr: val.nonceStr,
    package: val.packageValue,
    paySign: val.paySign,
    signType: val.signType,
    timeStamp: val.timeStamp
  }
  console.log(data, '0000')
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest', data,
    function (res) {
      if (res.err_msg === 'get_brand_wcpay_request:ok') { // 成功回调函数
        return fun(res, 'success')
      } else {
        var resData = res
        // 设置专用属性
        resData['hderrorcode'] = '-1'
        if (typeof (opt.error) === 'function') {
          return fun(resData, 'error')
        }
        if (res.err_msg === 'get_brand_wcpay_request:cancel') {
          Toast.fail('支付取消')
          if (typeof (opt.cancel) === 'function') {
            return fun(resData, cancel)
          }
        } else {
          Toast.fail('支付失败' + res.err_msg)
        }
        return resData
      }
    }
  )
}

export const isIos = () => {
  let equipmentType = ''
  let agent = navigator.userAgent.toLowerCase()
  let android = agent.indexOf('android')
  let iphone = agent.indexOf('iphone')
  let ipad = agent.indexOf('ipad')
  if (android !== -1) {
    equipmentType = false
  }
  if (iphone !== -1 || ipad !== -1) {
    equipmentType = true
  }
  return equipmentType
}
/**
 * TODO 目前只能传递一个图片，多个图片以后在做
 * @param option
 */
export const wxUploadImg = (option) => {
  option.num = option.num || 1
  option.num = option.num > 9 ? 9 : option.num
  if (option.type) {
    option.type = ['album', 'camera']
  }
  wxCallBack(function () {
    wx.chooseImage({
      count: option.num,
      sourceType: option.type,
      success: res => {
        let localIds001 = res.localIds
        wx.uploadImage({
          localId: localIds001[0], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: function (res1) {
            // let serverId = res1.serverId// 返回图片的服务器端ID
            // return serverId
            option.success(res1)
            // getMediaToOss(serverId).then(result => {
            //   option.success(result.data)
            // })
          }
        })
      }
    })
  })
}

export const isEmpty = (data) => {
  if (data === '' || data === null || data === undefined || data === 'undefined') {
    return true
  } else {
    return false
  }
}

/**
* @description: base64位图片转码文件流
* @param {type}
*/
export const base64toFile = (dataurl, filename = 'file') => {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let suffix = mime.split('/')[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  })
}

export const saveCookie = (key, data) => {
  Cookies.set(key, data, { expires: 1 })
}

export const getCookie = (key) => {
  const token = Cookies.get(key)
  if (token) return token
  else return false
}

// 调app扫码
export const scanOrcode = () => {
  console.log('调用app111扫描二维码功能')
  // 测试用户终端
  let u = navigator.userAgent
  let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
  console.log(isAndroid)
  let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
  console.log(isiOS)
  if (isAndroid) {
    console.log('isAndroid')
    //  给Android传递参数需要用 window.Android.注册的方法名({body:传输的数据} 来给native发送消息
    window.Android.scanQRCode('123')
  }
  if (isiOS) {
    console.log('isiOS')
    //  给iOS传递参数需要用 window.webkit.messageHandlers.注册的方法名.postMessage({body:传输的数据} 来给native发送消息
    window.webkit.messageHandlers.scanQRCode.postMessage('123')
  }
}
